package store.controller;

import com.alibaba.fastjson.JSONObject;
import store.dao.GoodsDAO;
import store.dao.RestockDAO;
import store.po.Goods;
import store.po.Restock;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/restock/add")
public class AddRestock extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Restock r = new Restock();
        r.setGoodsId(Integer.parseInt(request.getParameter("goods_id")));
        r.setPrice(Double.parseDouble(request.getParameter("price")));
        r.setStock(Integer.parseInt(request.getParameter("stock")));
        r.setSupplierId(Integer.parseInt(request.getParameter("supplier_id")));
        r.setTradeDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        try {
            new RestockDAO().save(r);
            GoodsDAO goodsDAO = new GoodsDAO();
            Goods g = goodsDAO.findById(r.getGoodsId());
            g.setStock(r.getStock() + g.getStock());
            goodsDAO.update(g);
            request.getRequestDispatcher("/goods/list?name="+g.getName()).forward(request,response);
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
